package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.DriverDao;
import com.hhs.storage.service.BaseRoleService;
import com.hhs.storage.service.CarFleetService;
import com.hhs.storage.service.DriverService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.ImgService;
import com.hhs.storage.util.SysUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2022-12-17
 */
@Service
@Transactional
public class DriverServiceImpl extends ServiceImpl<DriverDao, Driver> implements DriverService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private BaseRoleService roleService;
    @Resource
    ImgService imgService;
    @Resource
    private CarFleetService carFleetService;
    @Override
    public Map<String, Object> getAll(Driver driver, InputParam inputParam) {
        QueryWrapper ew = new QueryWrapper<Driver>();
        if(!StringUtils.isEmpty(driver.getName())){//名称查询
            ew.like("name",driver.getName());
        }
        if(!StringUtils.isEmpty(driver.getIdCard())){//身份证查询
            ew.eq("id_card",driver.getIdCard());
        }
        if(!StringUtils.isEmpty(driver.getPhone())){//手机号查询
            ew.eq("phone",driver.getPhone());
        }
        if(!StringUtils.isEmpty(driver.getCarFleetId())){//手机号查询
            ew.eq("car_fleet_id",driver.getCarFleetId());
        }
        //如果用户只是车队长，只能查询自身相关数据
        boolean isCDZ=roleService.hasOnlyRole(SysUtil.ROLE_FLAG_CDZ,SysUtil.getLoginUserId(request));
        if (isCDZ){//如果是车队长，查询条件只能查询与自己相关的车队数据
            //查询下属车队id
            List<CarFleet> carFleetList=
                    carFleetService.list(new QueryWrapper<CarFleet>().eq("principal_id",SysUtil.getLoginUserId(request)));
            List<String> carFleetIds=new ArrayList<>();
            for (int i = 0; i <carFleetList.size() ; i++) {
                CarFleet carFleet=carFleetList.get(i);
                carFleetIds.add(carFleet.getId());
            }
            //查询所属车队的车辆
            ew.in("car_fleet_id",carFleetIds.toArray());
        }
        ew.orderByDesc("create_time");
        Page<Driver> result = this.page(new Page<Driver>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<Driver> drivers=result.getRecords();
        for (int i = 0; i <drivers.size() ; i++) {
            Driver temp=drivers.get(i);
            CarFleet fleet=carFleetService.getById(temp.getCarFleetId());
            temp.setCarFleet(fleet);
        }
        map.put("rows", drivers);
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> addOrUpdate(Driver driver,String deleIdStr, MultipartFile[] driverLicenseList, MultipartFile[] healthCertificateList) {
        if(StringUtils.isEmpty(driver.getName()) ||
                StringUtils.isEmpty(driver.getIdCard())||
                StringUtils.isEmpty(driver.getCarFleetId())||
                StringUtils.isEmpty(driver.getPhone())){
            return ResponseInfo.error("参数错误");
        }
        //如果用户只是车队长，只能查询自身相关数据
        boolean isCDZ=roleService.hasOnlyRole(SysUtil.ROLE_FLAG_CDZ,SysUtil.getLoginUserId(request));
        if (isCDZ){//如果是车队长，新增编辑的车队只能是当前用户所有车队
            QueryWrapper<CarFleet> queryWrapper=new QueryWrapper<CarFleet>();
            queryWrapper.eq("principal_id",SysUtil.getLoginUserId(request));
            queryWrapper.eq("id",driver.getCarFleetId());
            int temp=carFleetService.count(queryWrapper);
            if (temp==0){
                return ResponseInfo.error("错误的所属车队");
            }
        }
        //新增
        if (StringUtils.isEmpty(driver.getId())) {
            return add(driver, driverLicenseList, healthCertificateList);
        } else {//修改
            return edit(driver, deleIdStr, driverLicenseList, healthCertificateList);
        }
    }

    private Map<String, Object> edit(Driver driver, String deleIdStr, MultipartFile[] driverLicenseList, MultipartFile[] healthCertificateList) {
        QueryWrapper<Driver> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id_card",driver.getIdCard()).ne("id",driver.getId());
        List<Driver> tempList=this.list(queryWrapper);
        if (tempList.size() > 0) {
            return ResponseInfo.error("身份证已存在，请重新输入");
        }
        queryWrapper.clear();
        queryWrapper.eq("phone",driver.getPhone()).ne("id",driver.getId());
        tempList=this.list(queryWrapper);
        if (tempList.size() > 0) {
            return ResponseInfo.error("手机号已存在，请重新输入");
        }
        //写入司机对象到数据库
        this.updateById(driver);
        //驾驶证有图片则保存图片
        if(driverLicenseList.length>0){
            imgService.upload( SysUtil.DRIVER_LICENSE,driver.getId(),driverLicenseList);
        }
        //驾驶证有图片则保存图片
        if(healthCertificateList.length>0){
            imgService.upload( SysUtil.HEALTH_CERTIFICATE,driver.getId(),healthCertificateList);
        }
        //删除图片
        if(!StringUtils.isEmpty(deleIdStr)){
            String[] deleIdArr = deleIdStr.split(",");
            if(deleIdArr.length>0){
                for (String id : deleIdArr) {
                    imgService.deleById(id);
                }
            }
        }
        return ResponseInfo.success("编辑成功");
    }

    private Map<String, Object> add(Driver driver, MultipartFile[] driverLicenseList, MultipartFile[] healthCertificateList) {
        QueryWrapper<Driver> queryWrapper=new QueryWrapper<>();
        driver.setCreateTime(LocalDateTime.now());
        driver.setId(SysUtil.UUID());
        queryWrapper.eq("id_card",driver.getIdCard());
        List<Driver> tempList=this.list(queryWrapper);
        if (tempList.size() > 0) {
            return ResponseInfo.error("身份证已存在，请重新输入");
        }
        queryWrapper.clear();
        queryWrapper.eq("phone",driver.getPhone());
        tempList=this.list(queryWrapper);
        if (tempList.size() > 0) {
            return ResponseInfo.error("手机号已存在，请重新输入");
        }
        //驾驶证有图片则保存图片
        if(driverLicenseList.length>0){
            imgService.upload( SysUtil.DRIVER_LICENSE,driver.getId(),driverLicenseList);
        }
        //驾驶证有图片则保存图片
        if(healthCertificateList.length>0){
            imgService.upload( SysUtil.HEALTH_CERTIFICATE,driver.getId(),healthCertificateList);
        }
        this.save(driver);
        return ResponseInfo.success("新增成功");
    }

    @Override
    public Map<String, Object> dele(String id) {
        this.baseMapper.deleteById(id);
        //找到司机的图片，删除图片
        Img img = new Img();
        img.setMainId(id);
        List<Img> imgList = imgService.getByMainId(img);
        for (Img img1 : imgList) {
            imgService.deleById(img1.getId());
        }
        return ResponseInfo.success("删除成功");
    }
}
